package com.smartcloud.scadmin.controller;

import com.smartcloud.common.util.ResultMessage;
import com.smartcloud.scadmin.core.config.WebSecurityConfig;
import com.smartcloud.scadmin.model.SysUser;
import com.smartcloud.scadmin.model.SysUserExample;
import com.smartcloud.scadmin.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.util.List;

@Api(value="登录",tags={"登录接口"})
@RestController
@RequestMapping("/user")  
public class UserController {  

	@Autowired   
    private SysUserService sysUserService;

	@ApiOperation(value="登录")
	@RequestMapping("/login")
	public ResultMessage login(@RequestParam("usercode") @NotNull String usercode, @RequestParam("password") @NotNull String password){
		SysUserExample example = new SysUserExample();
		example.createCriteria().andUserCodeEqualTo(usercode);
		List<SysUser> userList = sysUserService.selectByExample(example);
		if(!userList.isEmpty()){
			SysUser user = userList.get(0);
			if(password.equals(user.getPassword())){
				HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
				HttpSession session = request.getSession();
				session.setAttribute(WebSecurityConfig.SESSION_KEY, "user");
				session.setAttribute("currentUser", user);
				return new ResultMessage(true, user);
			}else{
				return new ResultMessage(false, "密码错误!");
			}
			
		}else{
			return new ResultMessage(false, "用户名不存在!");
		}
	}
	
//	@RequestMapping(value="/list")
//	public ResultMessage getUser(SysUser sysUser, @RequestParam("pageNo") int pageNo,@RequestParam("pageSize") int pageSize){
//		return new ResultMessage(ResultMessage.SUCCESS, sysUserService.selectAll(sysUser, pageNo, pageSize));
//	}

}  